<template>
  <div class="room-page" v-if="consultOrder.orderNo">
    <nav-bar title="医生问诊室" :back="back" />
    <RoomStatus
      :status="consultOrder.status"
      :countdown="consultOrder.countdown"
    />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <RoomMessage :list="list" />
    </van-pull-refresh>
    <RoomAction @send-image="sendImage" @send-text="sendText" />
  </div>
</template>

<script lang="ts" setup>
// 导入子组件
import RoomStatus from './components/room-status.vue'
import RoomMessage from './components/room-message.vue'
import RoomAction from './components/room-action.vue'
import { io, Socket } from 'socket.io-client'
import dayjs from 'dayjs'
import { onMounted, onUnmounted, ref, nextTick } from 'vue'
import { ApiRes } from '@/types/data'
import { ConsultOrderItem, Image } from '@/types/consult'
import request from '@/utils/request'
import { useRoute, useRouter } from 'vue-router'
import useStore from '@/store'
import { Message, TimeMessages } from '@/types/room'
import { MsgType } from '@/enums'
import { Toast } from 'vant'
const initialMsg = ref(true)
const { login } = useStore()
const route = useRoute()
const router = useRouter()
const consultOrder = ref({} as ConsultOrderItem)
// 返回
const back = () => {
  if (route.query.payResult) {
    router.push('/')
  } else {
    router.back()
  }
}
const getConsultOrder = async () => {
  const res = await request.get<ApiRes<ConsultOrderItem>>(
    'patient/consult/order/detail',
    {
      params: {
        orderId: route.query.orderId
      }
    }
  )

  if (res.data.code === 10000) {
    consultOrder.value = res.data.data
  }
}
let socket: Socket
const list = ref<Message[]>([])
onMounted(() => {
  getConsultOrder()
  initSocketAndListen()
})
onUnmounted(() => {
  socket.close()
})
// socket相关
const initSocketAndListen = () => {
  // 初始化socket
  socket = io(import.meta.env.VITE_BASEURL, {
    auth: {
      token: `Bearer ${login.info.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  // 连接上了
  socket.on('connect', () => {
    list.value = []
  })
  // 获取聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    console.log('---chatMsgList---', data)
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: {
          content: item.createTime
        },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    list.value.unshift(...arr)
    loading.value = false
    if (!data.length) {
      return Toast('没有聊天记录了')
    }

    nextTick(() => {
      if (initialMsg.value) {
        // 给服务器发消息，标记消息已读
        socket.emit('updateMsgStatus', arr[arr.length - 1].id)
        // 滚动到消息底部
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      }
    })
  })
  // 当医生端回复了消息
  socket.on('receiveChatMsg', async event => {
    console.log('---receiveChatMsg---', event)
    list.value.push(event)
    await nextTick()
    socket.emit('updateMsgStatus', event.id)
    // 滚动到底部
    window.scrollTo(0, document.body.scrollHeight)
  })
  // 错误消息
  socket.on('error', event => {
    console.log('---event---', event)
  })
  // 订单状态改变
  socket.on('statusChange', async () => {
    // 重新获取问诊订单
    getConsultOrder()
  })
}
// 获取聊天记录
const loading = ref(false)
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const onRefresh = () => {
  //向socket服务端发送数据 参数：pageSize: number, lastTime: string, orderId: string
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

// 发消息
// 发文字消息
const sendText = (text: string) => {
  socket.emit('sendChatMsg', {
    from: login.info.id,
    to: consultOrder.value.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}

// 发图片消息
const sendImage = (image: Image) => {
  socket.emit('sendChatMsg', {
    from: login.info.id,
    to: consultOrder.value.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: image
    }
  })
}
</script>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
